package com.ruoyi.product.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.company.domain.CompanyScope;
import com.ruoyi.company.service.ICompanyScopeServer;
import com.ruoyi.manufacturer.domain.DjManufacturer;
import com.ruoyi.material.domain.MaterialProduct;
import com.ruoyi.material.service.MateProductService;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductAll;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.product.domain.ProductRelation;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.product.service.AICodeService;
import com.ruoyi.product.service.ProductServer;
import com.ruoyi.productProof.service.ProductProofService;
import com.ruoyi.scope.domain.Scope;
import com.ruoyi.scope.mapper.ScopeMapper;
import com.ruoyi.scope.service.ScopeService;
import com.ruoyi.warehousing.domain.WarehouseStatisticsVo;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 产品信息处理
 */
@RestController
@RequestMapping("/business/product")
public class ProductController extends BaseController {

    @Autowired
    ScopeMapper scopeMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    MateProductService mateProductService;
    @Autowired
    private ProductServer productServer;
    @Autowired
    private ICompanyScopeServer iCompanyScopeServer;
    @Autowired
    private ProductProofService productProofService;
    @Autowired
    private ScopeService scopeService;
    @Autowired

    private AICodeService aiCodeService;
    private String prefix = "product";

    /**
     * 查询产品列表
     */
    @RequiresPermissions("business:product:view")
    @GetMapping()
    public String operlog() {
        return prefix + "/list";
    }


    @GetMapping("/selectScope")
    public List<Scope> selectScope() {
        List<Scope> list = scopeMapper.selectScope();
        return list;
    }


    @GetMapping("/selectMateProduct")
    public List<MaterialProduct> selectMateProduct() {
        List<MaterialProduct> list = mateProductService.selectMateProduct(SecurityUtils.getDeptId());
        return list;
    }


    @PostMapping("/importProduct")
    @ResponseBody
    public AjaxResult importCompany(MultipartFile file) {
        try (InputStream input = file.getInputStream()) {
            // KoAosCp koAosCp = aosCpService.importCompany(input);//业务层返回，我需要给前端返回，根据自己需求设置是否有需要返回
            productServer.importProduct(input);
        } catch (Exception e) {
            String msg = e.getMessage();
            if (StringUtils.isEmpty(msg)) {
                msg = e.getClass().getName();
            }
            e.printStackTrace();
        }
        return AjaxResult.success("");
    }

    /**
     * 查询产品列表
     */
    @RequiresPermissions("business:product:list")
    @GetMapping("/xxlist")
    @ResponseBody
    public TableDataInfo list(@RequestParam(value = "productName", required = false) String productName,
                              @RequestParam(value = "isProduction", required = false) String isProduction) {
        startPage();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Product product = new Product();
        product.setDeptId(sysUser.getDeptId());
        product.setProductName(productName);
        product.setIsProduction(isProduction);
        product.setCompanyId(sysUser.getDeptId());
        List<Product> list = productMapper.selectXxList(product);
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1); // 增加1个月

        for (Product product1 : list) {
            if (product1.getEndTime().getTime() < calendar.getTime().getTime()) {
                product1.setIsMature("1");
            } else {
                product1.setIsMature("0");
            }
        }



      /*  List<Product> list1 = productMapper.selectAuditSqList(product);
        List<String> longs = new ArrayList<>();
        List<Product> zzlist = new ArrayList<>();

        for (Product product1 : list) {
            longs.add(product1.getProductName());
        }

        if (list.size() != 0) {
            for (Product a1 : list1) {
                if (!longs.contains(a1.getProductName())) {
                    zzlist.add(a1);
                }
            }
            if (zzlist.size() == 0) {
                return getDataTable(list);
            } else {
                return getDataTable(zzlist);
            }
          *//*  for (Product a1 : list) {
                zzlist.add(a1);
            }*//*
        } else {

        }*/
        return getDataTable(list);
    }


    @GetMapping("/matureList")
    @ResponseBody
    public Map<String, Object> matureList() {

        Map<String, Object> resMap = new HashMap<>();
        List<Product> list = productMapper.selectMatureList(SecurityUtils.getDeptId());
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1); // 增加1个月
        List<Product> productList = new ArrayList<>();

        for (Product product : list) {
            if (product.getEndTime().getTime() < calendar.getTime().getTime()) {
                product.setIsMature("1");
                product.setRemark(dateToRemark(product));
                productList.add(product);
            }
        }

        resMap.put("list", productList);
        return resMap;
    }

    public static String dateToRemark(Product product) {
        // 当前日期
        LocalDate today = LocalDate.now();
        // Date 转 LocalDate
        LocalDate endDate = product.getEndTime().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        // 计算天数差
        long daysBetween = ChronoUnit.DAYS.between(today, endDate);

        StringBuilder sb = new StringBuilder();
        sb.append(product.getProductName());
        sb.append(daysBetween >= 0 ? "将于" + daysBetween + "天后过期，请尽快更换！" : "已过期" + Math.abs(daysBetween) + "天");

        String remark = product.getProductName() + "将于" + daysBetween + "天后过期，请尽快更换！";
        return sb.toString();
    }

    /*
    点击编辑后查询当前产品信息
     */
    @RequiresPermissions("business:product:list")
    @GetMapping("/list")
    @ResponseBody
    public Map<String, Object> xxlist(@RequestParam(value = "selectId") Long selectId,
                                      @RequestParam(value = "productId") Long productId,
                                      @RequestParam(value = "deptId") Long deptId) {
        Map<String, Object> resMap = new HashMap<>();
        Product product = new Product();
        product.setDeptId(deptId);
        product.setProductId(productId);
        product.setSelectId(selectId);
        List<Product> list = productMapper.selectProductList(product);
        List<ProductModel> productModels = productMapper.selectProductByModelId(product);
        List<Product> productList = productMapper.selectTimeList(productId, deptId);
        List<ProductRelation> relations = productMapper.selectProductRelation(productId);
        resMap.put("product", list);
        resMap.put("productModel", productModels);
        resMap.put("newProduct", productList);
        resMap.put("relations", relations);
        return resMap;
    }


    /**
     * 查询所有的生产商
     */
    @GetMapping("/selectManufacturer")
    public Map<String, Object> add() {
        Map<String, Object> resMap = new HashMap<>();
        //查询生产厂商， 返回的数据 jsonArray数组
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        JSONArray manufacturers = new JSONArray();
        for (DjManufacturer manufacturer : productServer.selectManufacturer(companyId)) {
            JSONObject obj = new JSONObject();
            obj.put("manufacturerId", manufacturer.getManufacturerId());
            obj.put("manufacturerName", manufacturer.getCompanyName());
            manufacturers.add(obj);
        }
        resMap.put("result", manufacturers);

        return resMap;
    }

    /**
     * 新增保存产品
     */
    @RequiresPermissions("business:product:add")
    @Log(title = "产品管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addSave(@RequestBody ProductAll productAll) {
        Product product = productAll.getProduct();
        String s = productServer.insertProduct(product, productAll.getProductModel(), productAll.getProductRelations());
        if (s.equals("0")) {
            return AjaxResult.error("产品的医疗器械注册证不唯一，请重新输入！");
        } else if (s.equals("1")) {
            return AjaxResult.success("插入成功");
        } else {
            return AjaxResult.error(s);
        }
    }

    /**
     * 添加产品图片信息
     */
    @GetMapping("/imgUpload")
    public String imgUpload() {
        return prefix + "/imgUpload";
    }

    /**
     * 添加产品图片信息
     */
    @GetMapping("/fileLook")
    public String fileLook() {
        return prefix + "/fileLook";
    }

    /**
     * 查询生产类别管理类别
     *
     * @param managementCategory 管理类别
     * @param mmap               视图
     * @return 结果
     */
    @PostMapping("/selectManagement/{managementCategory}")
    @ResponseBody
    public JSONArray selectManagement(@PathVariable("managementCategory") Long managementCategory, ModelMap mmap) {
        mmap.addAttribute("managementCategory", productServer.selectManagementCategory(managementCategory));
        //获取本公司的经营范围
        HashMap hashMap = new HashMap();
        hashMap.put("companyId", ShiroUtils.getSysUser().getCompanyId());
        hashMap.put("scopeClass", managementCategory);
        List<CompanyScope> list = iCompanyScopeServer.selectScopeByCompanyIdAndScopeClass(hashMap);

        JSONArray array = new JSONArray();
        for (CompanyScope companyScope : list) {
            JSONObject obj = new JSONObject();
            obj.put("managementCategory", companyScope.getScopeClass());//管理类别
            //根据 scopeid 查询 productClass
            Scope scope = scopeService.selectScopeById(companyScope.getScopeId());
            obj.put("scopeId", scope.getScopeId());
            obj.put("managementCategoryId", scope.getProductClass());//产品类别
            obj.put("productDesc", scope.getProductDesc());
            obj.put("scopeInfo", scope.getScopeInfo());
            if (scope.getProductRemark().length() == 0) {
                obj.put("productRemark", scope.getProductRemark());
            } else {
                obj.put("productRemark", "(" + scope.getProductRemark() + ")");
            }
            array.add(obj);
        }
        return array;
    }

    @GetMapping("/selectManagement/{managementCategory}")
    @ResponseBody
    public AjaxResult selectGetManagement(@PathVariable("managementCategory") Long managementCategory, ModelMap mmap) {

        mmap.addAttribute("managementCategory", productServer.selectManagementCategory(managementCategory));
        //获取本公司的经营范围
        HashMap hashMap = new HashMap();
        hashMap.put("companyId", ShiroUtils.getSysUser().getCompanyId());
        hashMap.put("scopeClass", managementCategory);
        List<CompanyScope> list = iCompanyScopeServer.selectScopeByCompanyIdAndScopeClass(hashMap);

        List<CompanyScope> users = new ArrayList<CompanyScope>();
        for (CompanyScope scope : list) {
            users.add(scope);
        }
        AjaxResult ajax = new AjaxResult();
        ajax.put("code", 200);
        ajax.put("value", list);
        return ajax;
    }

    /**
     * 删除产品
     */
    @RequiresPermissions("business:product:remove")
    @PostMapping("/remove/{productId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("productId") Long productId) {
        int i = productServer.removeProduct(productId);
        if (i == -1) {
            return AjaxResult.error("该产品正在使用，请清除关联关系");
        }
        return toAjax(i);
    }


    //查询生产厂商， 返回的数据 jsonArray数组
    public JSONArray selectManufacturer() {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long companyId = sysUser.getCompanyId();
        JSONArray manufacturers = new JSONArray();
        for (DjManufacturer manufacturer : productServer.selectManufacturer(companyId)) {
            JSONObject obj = new JSONObject();
            obj.put("manufacturerId", manufacturer.getManufacturerId());
            obj.put("manufacturerName", manufacturer.getCompanyName());
            manufacturers.add(obj);
        }
        return manufacturers;
    }

    /**
     * 修改保存产品信息
     */
    @RequiresPermissions("business:product:edit")
    @Log(title = "修改保存", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody ProductAll productAll) {

        String s = productServer.updateProduct(productAll);
        if (s.equals("0")) {
            return AjaxResult.error("产品的医疗器械注册证不唯一，请重新输入！");
        } else {
            return AjaxResult.success("修改成功");
        }
    }

    /**
     * 查询产品型号规格是否唯一
     */
//    @RequiresPermissions("business:product:selectProductProductType")
    @PostMapping("/selectProductProductType")
    @ResponseBody
    public int selectProductProductType(@Param("deptId") Long deptId, @Param("productType") String productType) {
        ProductModel productModel = new ProductModel();
        productModel.setDeptId(deptId);
        productModel.setProductType(productType);
        Long s = productServer.selectProductProductType(productModel);
        if (s == null) {
            return 0;
        } else {
            return 1;
        }
    }

    /**
     * 查询产品型号为一码是否唯一
     */
    @PostMapping("/selectProductModelCode")
    @ResponseBody
    public int selectProductModelCode(@Param("deptId") Long deptId, @Param("modelCode") String modelCode) {
        ProductModel productModel = new ProductModel();
        productModel.setDeptId(deptId);
        productModel.setModelCode(modelCode);
        Long s = productServer.selectProductModelCode(productModel);
        if (s == null) {
            return 0;
        } else {
            return 1;
        }
    }

    /**
     * 根据产品ID和产品型号修改对应的 选择查询的天数 和 采购周期的时间
     * params:{
            "productId": '产品ID',
            "productType":"产品型号",
            "purchase_cycle":"60",
            "select_cycle":"180"
     * }
     * @param params
     * @return
     */
    @PutMapping("/updateByPiAPt")
    public AjaxResult updateByPiAPt(@RequestBody Map<String, Object> params) {
        List<WarehouseStatisticsVo> result = productServer.updateByPiAPt(params);
        return AjaxResult.success(result);
    }

}
